//https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
//从前序和中序遍历构造二叉树
//给定两个整数数组 preorder 和 inorder ，其中 preorder 是二叉树的先序遍历， inorder 是同一棵树的中序遍历，请构造二叉树并返回其根节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    typedef vector<int>::iterator ittor;

    TreeNode* Create(ittor& it, ittor left, ittor right)
    {
        if(left > right)
            return nullptr;

        TreeNode* root = new TreeNode(*it);
        ittor mid = left;
        while(*it != *mid){++mid;}
        ++it;
        root->left = Create(it, left, mid - 1);
        root->right = Create(it, mid + 1, right);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty())
            return nullptr;

        TreeNode* root = new TreeNode(preorder[0]);
        auto it = preorder.begin();
        auto in = inorder.begin();
        while(*it != *in){++in;}
        ++it;
        root->left = Create(it, inorder.begin(), in - 1);
        root->right = Create(it, in + 1, inorder.end() - 1);
        return root;
    }
};